/**
 * 余额记录明细
 * author wim
 */
import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_cupertino_date_picker/flutter_cupertino_date_picker.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:panda/base/SignType.dart';
import 'package:panda/entity/common_entity.dart';
import 'package:panda/http/Api.dart';
import 'package:panda/http/HttpUtil.dart';
import 'package:panda/util/AppSaveInfoUtil.dart';
import 'package:panda/util/DateUtils.dart';
import 'package:panda/util/SignUtil.dart';

import '../base/Constant.dart';

class BalanceRecordPage extends StatefulWidget {
  String type;
  BalanceRecordPage({Key key, this.type}) : super(key: key);
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return BalanceRecordView();
  }
}

class BalanceRecordView extends State<BalanceRecordPage> {
  List<CommonEntityDataData> dataList = new List();
  int page = 1;
  String token = "", time1 = "开始日期", time2 = "结束日期";
  EasyRefreshController _controller = EasyRefreshController();
  String action = "";
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getString(TOKEN).then((value) {
      token = value;
      loadList();
    });
  }

  loadList() async {
    Map map = new Map();
    map['token'] = token;
    map['p'] = page;
      if (!time1.contains("开始")) {
      map['start'] = time1;
    }
    if (!time2.contains("结束")) {
      map['end'] = time2;
    }
    if (widget.type != "2") {
      map['action'] = action;
    }
    map['per'] = "10";
     print(map);
    Response<String> response = await HttpUtil().post(
        widget.type == "1"
            ? Api.POINT_RECORD
            : widget.type == "2" ? Api.BALANCE_RECORD : Api.BALANCE_RECORD,
        data: getSign(map));
    Map userMap = json.decode(response.data);
    print(response);
    if (userMap['code'] != 1) {
      Fluttertoast.showToast(msg: userMap['msg']);
      return;
    }
    CommonEntityEntity meListEntity = new CommonEntityEntity.fromJson(userMap);

    if (mounted)
      setState(() {
        if (page == 1) {
          dataList.clear();
          dataList.addAll(meListEntity.data.datas);
          _controller.finishRefresh();
          _controller.resetLoadState();
        } else {
          dataList.addAll(meListEntity.data.datas);
          _controller.finishLoad(noMore: meListEntity.data.datas.length == 0);
        }
      });
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);

    return new Scaffold(
      appBar: new AppBar(
        title: Text(
            widget.type == "1"
                ? "积分变动明细"
                : widget.type == "2" ? '提现明细' : '余额明细',
            style: TextStyle(
                fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE),
                color: Colors.black)),
        backgroundColor: Colors.white,
        brightness: Brightness.light,
        centerTitle: true,
        iconTheme: new IconThemeData(color: Colors.black),
        elevation: 0.5,
        actions: <Widget>[
          Offstage(
            offstage: widget.type != null && widget.type != "1",
            child: GestureDetector(
              child: Container(
                alignment: Alignment.center,
                padding: EdgeInsets.all(10),
                child: Text('筛选',
                    style: TextStyle(
                        color: mainColor,
                        fontSize: ScreenUtil.getInstance().setSp(30))),
              ),
              onTap: () async {
                action = widget.type == "1"
                    ? await showModalBottomSheet(
                        context: context,
                        builder: (BuildContext context) {
                          return Container(
                            child: Column(
                              children: <Widget>[
                                GestureDetector(
                                  child: Container(
                                    alignment: Alignment.center,
                                    padding: EdgeInsets.all(
                                        ScreenUtil.getInstance().setHeight(18)),
                                    child: Text('消费',
                                        style: TextStyle(
                                          fontSize: ScreenUtil.getInstance()
                                              .setHeight(18),
                                        )),
                                  ),
                                  behavior: HitTestBehavior.opaque,
                                  onTap: () {
                                    Navigator.pop(context, '7');
                                  },
                                ),
                                Divider(
                                  height: 1,
                                ),
                                GestureDetector(
                                  child: Container(
                                    alignment: Alignment.center,
                                    padding: EdgeInsets.all(
                                        ScreenUtil.getInstance().setHeight(18)),
                                    child: Text('扣除',
                                        style: TextStyle(
                                          fontSize: ScreenUtil.getInstance()
                                              .setHeight(18),
                                        )),
                                  ),
                                  behavior: HitTestBehavior.opaque,
                                  onTap: () {
                                    Navigator.pop(context, '13');
                                  },
                                ),
                                Divider(
                                  height: 1,
                                ),
                                GestureDetector(
                                  child: Container(
                                    alignment: Alignment.center,
                                    padding: EdgeInsets.all(
                                        ScreenUtil.getInstance().setHeight(18)),
                                    child: Text('退款',
                                        style: TextStyle(
                                          fontSize: ScreenUtil.getInstance()
                                              .setHeight(18),
                                        )),
                                  ),
                                  behavior: HitTestBehavior.opaque,
                                  onTap: () {
                                    Navigator.pop(context, '8');
                                  },
                                ),
                                Divider(
                                  height: 1,
                                ),
                                GestureDetector(
                                  child: Container(
                                    alignment: Alignment.center,
                                    padding: EdgeInsets.all(
                                        ScreenUtil.getInstance().setHeight(18)),
                                    child: Text('个人充值',
                                        style: TextStyle(
                                          fontSize: ScreenUtil.getInstance()
                                              .setHeight(18),
                                        )),
                                  ),
                                  behavior: HitTestBehavior.opaque,
                                  onTap: () {
                                    Navigator.pop(context, '19');
                                  },
                                ),
                                Divider(
                                  height: 1,
                                ),
                                GestureDetector(
                                  child: Container(
                                    alignment: Alignment.center,
                                    padding: EdgeInsets.all(
                                        ScreenUtil.getInstance().setHeight(18)),
                                    child: Text('平台充值',
                                        style: TextStyle(
                                          fontSize: ScreenUtil.getInstance()
                                              .setHeight(18),
                                        )),
                                  ),
                                  behavior: HitTestBehavior.opaque,
                                  onTap: () {
                                    Navigator.pop(context, '14');
                                  },
                                ),
                                Divider(
                                  height: 1,
                                ),
                              ],
                            ),
                          );
                        })
                    : await showModalBottomSheet(
                        context: context,
                        builder: (BuildContext context) {
                          return Container(
                            height:
                                ScreenUtil.getInstance().setHeight(18) * 22 + 5,
                            child: Column(
                              children: <Widget>[
                                GestureDetector(
                                  child: Container(
                                    alignment: Alignment.center,
                                    padding: EdgeInsets.all(
                                        ScreenUtil.getInstance().setHeight(18)),
                                    child: Text('提现',
                                        style: TextStyle(
                                          fontSize: ScreenUtil.getInstance()
                                              .setHeight(18),
                                        )),
                                  ),
                                  behavior: HitTestBehavior.opaque,
                                  onTap: () {
                                    Navigator.pop(context, '1');
                                  },
                                ),
                                Divider(
                                  height: 1,
                                ),
                                GestureDetector(
                                  child: Container(
                                    alignment: Alignment.center,
                                    padding: EdgeInsets.all(
                                        ScreenUtil.getInstance().setHeight(18)),
                                    child: Text('消费',
                                        style: TextStyle(
                                          fontSize: ScreenUtil.getInstance()
                                              .setHeight(18),
                                        )),
                                  ),
                                  behavior: HitTestBehavior.opaque,
                                  onTap: () {
                                    Navigator.pop(context, '13');
                                  },
                                ),
                                Divider(
                                  height: 1,
                                ),
                                GestureDetector(
                                  child: Container(
                                    alignment: Alignment.center,
                                    padding: EdgeInsets.all(
                                        ScreenUtil.getInstance().setHeight(18)),
                                    child: Text('奖励',
                                        style: TextStyle(
                                          fontSize: ScreenUtil.getInstance()
                                              .setHeight(18),
                                        )),
                                  ),
                                  behavior: HitTestBehavior.opaque,
                                  onTap: () {
                                    Navigator.pop(context, '5');
                                  },
                                ),
                                Divider(
                                  height: 1,
                                ),
                                GestureDetector(
                                  child: Container(
                                    alignment: Alignment.center,
                                    padding: EdgeInsets.all(
                                        ScreenUtil.getInstance().setHeight(18)),
                                    child: Text('退款',
                                        style: TextStyle(
                                          fontSize: ScreenUtil.getInstance()
                                              .setHeight(18),
                                        )),
                                  ),
                                  behavior: HitTestBehavior.opaque,
                                  onTap: () {
                                    Navigator.pop(context, '12');
                                  },
                                ),
                                Divider(
                                  height: 1,
                                ),
                                GestureDetector(
                                  child: Container(
                                    alignment: Alignment.center,
                                    padding: EdgeInsets.all(
                                        ScreenUtil.getInstance().setHeight(18)),
                                    child: Text('差价',
                                        style: TextStyle(
                                          fontSize: ScreenUtil.getInstance()
                                              .setHeight(18),
                                        )),
                                  ),
                                  behavior: HitTestBehavior.opaque,
                                  onTap: () {
                                    Navigator.pop(context, '15');
                                  },
                                ),
                                Divider(
                                  height: 1,
                                ),
                                 GestureDetector(
                                  child: Container(
                                    alignment: Alignment.center,
                                    padding: EdgeInsets.all(
                                        ScreenUtil.getInstance().setHeight(18)),
                                    child: Text('提成',
                                        style: TextStyle(
                                          fontSize: ScreenUtil.getInstance()
                                              .setHeight(18),
                                        )),
                                  ),
                                  behavior: HitTestBehavior.opaque,
                                  onTap: () {
                                    Navigator.pop(context, '14');
                                  },
                                ),
                                Divider(
                                  height: 1,
                                ),
                              ],
                            ),
                          );
                        });
                page = 1;
                loadList();
              },
              behavior: HitTestBehavior.opaque,
            ),
          )
        ],
      ),
      body: new Container(
        color: divideColor,
        child: Column(
          children: <Widget>[
              Container(
              color: f0Color,
              padding:
                  EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_20)),
              child: Row(
                children: <Widget>[
                  Expanded(child: Center()),
                  GestureDetector(
                    child: Container(
                      padding: EdgeInsets.fromLTRB(10, 0, 0, 0),
                      decoration: BoxDecoration(
                          border: Border.all(color: black_99, width: 1),
                          borderRadius: BorderRadius.circular(3)),
                      child: Row(children: <Widget>[
                        Text('$time1',
                            style: TextStyle(
                                color: black_99,
                                fontSize: ScreenUtil.getInstance()
                                    .setSp(SMALL_FONT_SIZE))),
                        Icon(
                          Icons.arrow_drop_down,
                          color: black_99,
                        )
                      ]),
                    ),
                    onTap: () {
                      DatePicker.showDatePicker(context,
                          pickerTheme: DateTimePickerTheme(
                            showTitle: true,
                            confirm:
                                Text('确定', style: TextStyle(color: Colors.red)),
                            cancel: Text('取消',
                                style: TextStyle(color: Colors.cyan)),
                          ),
                          minDateTime: DateTime.parse("1980-05-01"),
                          dateFormat: "yyyy-MM-dd",
                          pickerMode: DateTimePickerMode.date,
                          locale: DateTimePickerLocale.zh_cn, onCancel: () {
                        debugPrint("onCancel");
                      }, onConfirm: (dateTime, List<int> index) {
                        setState(() {
                          time1 = DateUtils.instance.getFormartData(
                              timeSamp: dateTime.millisecondsSinceEpoch,
                              format: "yyyy-MM-dd");
                          page = 1;
                          loadList();
                        });
                      });
                    },
                  ),
                  Text('  至  ',
                      style: TextStyle(
                          color: black,
                          fontSize: ScreenUtil.getInstance()
                              .setSp(NORMAL_FONT_SIZE))),
                  GestureDetector(
                    child: Container(
                      padding: EdgeInsets.fromLTRB(10, 0, 0, 0),
                      decoration: BoxDecoration(
                          border: Border.all(color: black_99, width: 1),
                          borderRadius: BorderRadius.circular(3)),
                      child: Row(children: <Widget>[
                        Text('$time2',
                            style: TextStyle(
                                color: black_99,
                                fontSize: ScreenUtil.getInstance()
                                    .setSp(SMALL_FONT_SIZE))),
                        Icon(
                          Icons.arrow_drop_down,
                          color: black_99,
                        )
                      ]),
                    ),
                    onTap: () {
                      DatePicker.showDatePicker(context,
                          pickerTheme: DateTimePickerTheme(
                            showTitle: true,
                            confirm:
                                Text('确定', style: TextStyle(color: Colors.red)),
                            cancel: Text('取消',
                                style: TextStyle(color: Colors.cyan)),
                          ),
                          minDateTime: DateTime.parse("1980-05-01"),
                          dateFormat: "yyyy-MM-dd",
                          pickerMode: DateTimePickerMode.date,
                          locale: DateTimePickerLocale.zh_cn, onCancel: () {
                        debugPrint("onCancel");
                      }, onConfirm: (dateTime, List<int> index) {
                        setState(() {
                          time2 = DateUtils.instance.getFormartData(
                              timeSamp: dateTime.millisecondsSinceEpoch,
                              format: "yyyy-MM-dd");
                          page = 1;
                          loadList();
                        });
                      });
                    },
                  ),
                  Expanded(child: Center()),
                  GestureDetector(
                    onTap: () {
                      time1 = "开始日期";
                      time2 = "结束日期";
                      loadList();
                    },
                    child: Text('   全部日期   ',
                        style: TextStyle(
                            fontSize: ScreenUtil.getInstance()
                                .setSp(NORMAL_FONT_SIZE),
                            color: black_99)),
                  )
                ],
              ),
            ),
          
            Expanded(
                child: new EasyRefresh(
              enableControlFinishRefresh: true,
              enableControlFinishLoad: true,
              controller: _controller,
              header: MaterialHeader(),
              footer: MaterialFooter(),
              child: ListView.separated(
                  itemBuilder: _renderRow,
                  separatorBuilder: (BuildContext context, int index) {
                    return Container(
                      color: divideColor,
                      height: 1,
                    );
                  },
                  itemCount: dataList.length),
              onRefresh: () async {
                page = 1;
                loadList();
              },
              onLoad: () async {
                page++;
                loadList();
              },
            )),
          ],
        ),
      ),
    );
  }

  Widget _renderRow(BuildContext context, int index) {
    return new GestureDetector(
      child: new Container(
        color: Colors.white,
        padding: EdgeInsets.all(8.0),
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            new Row(
              children: <Widget>[
                Expanded(
                  flex: 1,
                  child: Text(
                    dataList[index].action_zh,
                    style: TextStyle(
                        fontSize: ScreenUtil.getInstance()
                            .setSp(NORMAL_FONT_SIZE - 1),
                        color: Colors.black),
                  ),
                ),
                Text(
                  dataList[index].action_symbol +
                      (widget.type == "1"
                          ? dataList[index].point
                          : dataList[index].money),
                  style: TextStyle(
                      fontSize:
                          ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE + 2),
                      color: mainColor),
                ),
              ],
            ),
             Offstage(
              offstage: dataList[index].referrer_name==null||dataList[index].referrer_name=="null"||dataList[index].referrer_name=='',
              child: Text("所属店铺: "+dataList[index].referrer_name, style: TextStyle(
                      fontSize:
                          ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE-4),
                      color: Colors.black87)),
            ),
            Offstage(
              offstage: dataList[index].action!="15"&&dataList[index].action!="12"&&dataList[index].action!="13"&&dataList[index].action!="5"&&dataList[index].action!="7"&&dataList[index].action!="8"&&dataList[index].action!="14",
              child: Text("订单号: "+dataList[index].order_num, style: TextStyle(
                      fontSize:
                          ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE-4),
                      color: Colors.black87)),
            ),
            Offstage(
              offstage: dataList[index].action!="15"&&dataList[index].action!="12"&&dataList[index].action!="13"&&dataList[index].action!="5"&&dataList[index].action!="7"&&dataList[index].action!="8"&&dataList[index].action!="14",
              child: Text("商品名称: "+dataList[index].order_name, style: TextStyle(
                      fontSize:
                          ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE-4),
                      color: Colors.black87)),
            ),
            Container(
              padding: EdgeInsets.fromLTRB(
                  0, ScreenUtil.getInstance().setHeight(5), 0, 0),
              child: new Row(
                children: <Widget>[
                  Expanded(
                    flex: 1,
                    child: Text(
                      dataList[index].create_time,
                      style: TextStyle(
                          fontSize: ScreenUtil.getInstance()
                              .setSp(NORMAL_FONT_SIZE - 3),
                          color: Colors.black),
                    ),
                  ),
                  Text(
                    (widget.type == "1" ? "积分: " : "余额: ") +
                        (widget.type == "1"
                            ? dataList[index].all_point
                            : dataList[index].all_money),
                    style: TextStyle(
                        fontSize: ScreenUtil.getInstance()
                            .setSp(NORMAL_FONT_SIZE - 5),
                        color: Colors.black87),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
      onTap: () {},
    );
  }
}
